import logging
import allure
from airtest.core.api import *
from airtest.core.settings import Settings

from common.commin.commin import read_ini
from common.log.log import log
# from common.video.shots import pc_shots
from config.conf import BASE_DIR


class AirtestBase:
    """
    # 基类——把一些常用的操作封住到base.py文件上
    """

    def __init__(self, title="花王云购"):
        auto_setup(__file__, devices=[f"Windows:///?title_re={title}"])
        logger = logging.getLogger("airtest")
        logger.setLevel(logging.ERROR)  # 设置airtest日志级别为INFO，默认是DEBUG，打印太多垃圾日志了
        sleep(1)

    def airtest_click(self, filename=""):
        touch(Template(filename=filename))

    @allure.step('图片断言，判断目标存在')
    def assert_png(self, txt='断言目标', filename=""):
        """
        图片断言，判断目标存在
        """
        try:
            assert_exists(Template(filename=filename))
            # with allure.step('检查成功时刻截图..'):
            #     allure.attach(pc_shots(), "截图", allure.attachment_type.PNG)
            log.info("{}-断言成功,目标存在".format(txt))
            return True
        except Exception as e:
            log.error(f'断言过程中出现异常，为{e}')
            raise e

    @allure.step('图片断言（方式二），判断目标存在')
    def assert_png_2(self, filename=""):
        """
        图片断言（方式二），判断目标存在
        """
        try:
            if exists_1(filename):
                # with allure.step('检查成功时刻截图..'):
                #     allure.attach(pc_shots(), "截图", allure.attachment_type.PNG)
                log.info(f"断言成功,目标存在，目标元素图片为：{filename}")
                return True
            else:
                log.error(f'不存在该元素图片：{filename}')
                raise FileNotFoundError
        except FileNotFoundError as e:
            log.error('定位不到图片可能是被遮挡，重试！！！！！')
            if exists_1(BASE_DIR + "/element_picture/快捷键-首页.png"):
                AirtestBase().click_5(BASE_DIR + "/element_picture/快捷键-收缩2.png")
            if exists_1(filename):
                # with allure.step('检查成功时刻截图..'):
                #     allure.attach(pc_shots(), "截图", allure.attachment_type.PNG)
                log.info("断言成功,目标存在")
                return True
            log.error(f'断言过程中出现异常，为{e}')
            return False

    @allure.step('图片断言，判断目标不存在')
    def assert_not_png(self, filename=""):
        """
        图片断言，判断目标不存在
        """
        try:
            if not exists(Template(filename)):
                # with allure.step('检查成功时刻截图..'):
                #     allure.attach(pc_shots(), "截图", allure.attachment_type.PNG)
                log.info(f"断言成功,目标元素不存在：{filename}")
                return True
            else:
                log.error(f'仍然存在该元素图片：{filename}')
                return False
        except Exception as e:
            log.error(f'图片断言，判断目标不存在过程中出现异常，为{e}')
            raise False

    def get_png(self, txt):
        # msg描述测试点
        png_name = BASE_DIR + "/screenshot/{}_{}.png".format(txt, time.strftime("%Y-%m-%d-%H-%M-%S"))
        snapshot(filename=png_name, msg=txt)
        return snapshot(filename=png_name, msg=txt)

    # 文字断言
    def assert_txt(self, png):
        # 只能读取数字-------因为没中文包
        # image = Image.open(png)
        # txt = pytesseract.image_to_string(image)
        print("---------------------------")
        # print(txt)
        # return txt
        pass

    """显示等来"""

    def wait(self):
        pass

    # 原生桌面长按
    def long_press(self, txt):
        pass

    # 图片长按/长按
    def long_png_press(self, filename=""):
        touch(Template(filename=filename), duration=1)

    def slide(self):
        # print("获取屏幕大小：", self.r.get_screen_size())
        pass

    @allure.step('键盘上下左右按键实现滑动')
    def up_or_down(self, action='up', num=15):
        """
        模拟键盘的上下左右按键，实现小程序屏幕的四个方向滑动
        """
        sleep_time = 0.1
        if action == 'down':
            log.info('———向下按键———')
            for i in range(num):
                sleep(sleep_time)
                keyevent("{DOWN}")  # 向下
        elif action == 'up':
            log.info('———向上按键———')
            for i in range(num):
                sleep(sleep_time)
                keyevent("{UP}")  # 向上
        elif action == 'left':
            keyevent("{LEFT}")  # 向左
            log.info('向左按键')
        elif action == 'right':
            keyevent("{RIGHT}")  # 向右
            log.info('向右按键')

    def up_down_search_element_and_click(self, element, num=2, mode=1):
        """
        上下查找元素，并点击
        mode=1: 找到元素后点击
        mode=2：找到元素即可，返回True
        """
        try:
            for i in range(num):
                if not exists(Template(element)):
                    log.info(f'没找到元素{element},现上下滑动查找')
                    self.up_or_down('down')
                else:
                    if mode == 1:
                        AirtestBase().click_5(element)
                        return True
                    elif mode == 2:
                        log.info(f'找到了元素{element}')
                        return True
            raise FileNotFoundError
        except Exception as e:
            log.error(f'上下查找元素出现异常为：{e}')
            raise e

    """filename---图片"""
    """threshold---识别度"""
    """target_pos---位置---默认为中心点击，6位右边，8位底部中心以此类推"""
    """rgb---黑白处理后识别----默认为False,开的话为True"""

    # 中心点击
    def click_5(self, filename="", threshold=0.75):
        Settings.FIND_TIMEOUT = 10
        try:
            # threshold = read_ini()['airtest_parameter']['threshold']
            touch(Template(filename=filename, threshold=float(threshold)))
        except Exception as e:
            log.error(f'中心点击出现异常为：{e}')
            raise e

    # 中心点击和输入
    def click_5_input(self, txt, filename=""):
        touch(Template(filename=filename))
        text(txt, enter=False)

    def input(self, txt):
        text(txt, enter=False)

    # 右边沿点击和输入
    def click_6(self, filename=""):
        touch(Template(filename=filename, target_pos=6))

    def click_6_input(self, txt, filename=""):
        touch(Template(filename=filename, target_pos=6))
        text(txt, enter=False)

    # 底部中间点击
    def click_8(self, filename=""):
        touch(Template(filename=filename, target_pos=8))

    def click_9(self, filename=""):
        touch(Template(filename=filename, target_pos=9))

    def click_3(self, filename=""):
        touch(Template(filename=filename, target_pos=3))

    def click_4(self, filename=""):
        touch(Template(filename=filename, target_pos=4, threshold=0.75))

    # 底部中间点击输入
    def click_8_input(self, txt, filename=""):
        touch(Template(filename=filename, target_pos=8))
        text(txt, enter=False)

    # 清除文本
    def clear_txt(self, location):
        for i in range(location):
            keyevent("KEYCODE_DEL")

    # 返回按钮
    def back_btn(self):
        keyevent("KEYCODE_BACK")

    # 删除图片和日记
    pass

    @allure.step('返回上一页')
    def go_back(self, num):
        """
        返回
        num：返回次数
        """
        element_1 = BASE_DIR + r"/element_picture/白底返回.png"
        element_2 = BASE_DIR + r"/element_picture/返回2.png"
        element_3 = BASE_DIR + r"/element_picture/返回3.png"
        for i in range(num):
            if exists_1(element_1):
                log.info('返回上一页')
                self.click_5(element_1)
                sleep(1)
            elif exists_1(element_2):
                log.info('返回上一页')
                self.click_5(element_2)
                sleep(1)
            elif exists_1(element_3):
                log.info('返回上一页')
                self.click_5(element_3)
                sleep(1)

    @allure.step('返回首页')
    def go_home(self, mode=0):
        """
        返回首页
        mode=0: 通过快捷方式
        mode=1: 商品详情页，点击“首页”
        :return:
        """
        try:
            from po.jinhua.applets_po.home.home_page import HomePage
            if mode == 0:
                log.info('快捷键方式返回首页')
                if not exists(Template(BASE_DIR + r"/element_picture/快捷键-首页.png")):
                    self.click_5(BASE_DIR + r"/element_picture/快捷键-收缩.png")
                    sleep(1)
                    self.click_5(BASE_DIR + r"/element_picture/快捷键-首页.png")
                    sleep(1)
                    return HomePage()
                else:
                    self.click_5(BASE_DIR + r"/element_picture/快捷键-首页.png")
                    sleep(1)
                    return HomePage()
            elif mode == 1:
                log.info('商品详情页，点击首页返回')
                self.click_5(BASE_DIR + r"/element_picture/商品详情页/首页.png")
                self.click_5(BASE_DIR + r"/element_picture/X.png")
                return HomePage()
            elif mode == 2:
                log.info('直接点击底部“首页”返回')
                element_1 = BASE_DIR + r"/element_picture/首页.png"
                element_2 = BASE_DIR + r"/element_picture/首页_灰色.png"
                if exists_1(element_1):
                    self.click_5(element_1)
                    return HomePage()
                else:
                    self.click_5(element_2)
                    return HomePage()

        except Exception as e:
            log.error(f'返回首页出现异常，为：{e}')
            raise e

    @allure.step('从微信中打开花王云购小程序')
    def open_huawang_applets(self):
        """
        从微信中打开花王云购小程序
        """
        try:
            sleep(3)
            touch(Template(BASE_DIR + r"/element_picture/微信/demo.png"))
            sleep(3)
            touch(Template(BASE_DIR + r"/element_picture/微信/花王云购+小程序.png"))
            sleep(5)
        except TargetNotFoundError:
            touch(Template(BASE_DIR + r"/element_picture/微信/demo.png"))
            sleep(3)
            touch(Template(BASE_DIR + r"/element_picture/微信/花王云购+小程序.png"))
            sleep(5)

    @allure.step('花王云购小程序-微信登录')
    def login_hw(self):
        """花王云购小程序-微信登录"""
        try:
            drives = AirtestBase('花王云购')
            log.info('开始微信登录小程序')
            if not exists(Template(BASE_DIR + r"/element_picture/我的/登录/微信登录.png")):
                drives.click_5(BASE_DIR + r"/element_picture/我的/登录/登录.png")
                drives.click_5(BASE_DIR + r"/element_picture/我的/登录/微信登录.png")
                drives.click_5(BASE_DIR + r"/element_picture/我的/登录/允许.png")
                drives.click_5(BASE_DIR + r"/element_picture/首页_灰色.png")
                log.info('登录成功！')
            elif exists_1(BASE_DIR + r"/element_picture/我的/登录/微信登录.png"):
                drives.click_5(BASE_DIR + r"/element_picture/我的/登录/微信登录.png")
                drives.click_5(BASE_DIR + r"/element_picture/我的/登录/允许.png")
                drives.click_5(BASE_DIR + r"/element_picture/首页_灰色.png")
                log.info('登录成功！')
        except Exception as e:
            log.error(f'花王云购小程序-微信登录出现异常，为：{e}')
            raise e


@allure.step('返回首页')
def go_home_2():
    """
    适配各种场景下的返回首页
    """

    log.info('返回首页')
    element_1 = BASE_DIR + r"/element_picture/快捷键-首页.png"
    element_2 = BASE_DIR + r"/element_picture/白底返回.png"
    element_3 = BASE_DIR + r"/element_picture/返回2.png"
    element_4 = BASE_DIR + r"/element_picture/返回3.png"
    element_5 = BASE_DIR + r"/element_picture/首页.png"
    element_6 = BASE_DIR + r"/element_picture/首页_灰色.png"
    element_7 = BASE_DIR + r"/element_picture/首页/花王云购LOGO.png"  # 回到首页且出现该logo，异常恢复才结束
    element_8 = BASE_DIR + r"/element_picture/X.png"
    element_9 = BASE_DIR + r"/element_picture/X_2.png"
    element_10 = BASE_DIR + r"/element_picture/左上角返回首页按钮.png"
    for i in range(10):
        if exists_1(element_9):
            AirtestBase().click_5(element_9)
        elif exists_1(element_5):
            AirtestBase().click_5(element_5)
            if exists_1(element_8):
                AirtestBase().click_5(element_8)
            elif exists_1(element_7):
                log.info('完成！')
                break
            AirtestBase().up_or_down('up')
        elif exists_1(element_6):
            AirtestBase().click_5(element_6)
            if exists_1(element_8):
                AirtestBase().click_5(element_8)
            elif exists_1(element_7):
                log.info('完成！')
                break
            AirtestBase().up_or_down('up')
        elif exists_1(element_1):
            AirtestBase().click_5(element_1)
        elif exists_1(element_10):
            AirtestBase().click_5(element_10)
        elif exists_1(element_2):
            AirtestBase().click_5(element_2)
        elif exists_1(element_3):
            AirtestBase().click_5(element_3)
        elif exists_1(element_4):
            AirtestBase().click_5(element_4)
        elif exists_1(element_8):
            AirtestBase().click_5(element_8)


# def go_home_level_1():
#     """
#     悬浮球返回首页（商品详情页、个人中心-我的订单）
#     """
#     try:
#         element_1 = BASE_DIR + r"/element_picture/快捷键-收缩.png"
#         element_2 = BASE_DIR + r"/element_picture/快捷键-收缩2.png"
#         element_3 = BASE_DIR + r"/element_picture/快捷键-首页.png"
#
#         element_7 = BASE_DIR + r"/element_picture/首页/花王云购LOGO.png"  # 回到首页且出现该logo，异常恢复才结束
#         element_8 = BASE_DIR + r"/element_picture/X.png"
#         if exists_1(element_1) or exists_1(element_2):
#             log.info('通过悬浮球返回首页')
#             if exists_1(element_3):
#                 AirtestBase().click_5(element_3)
#                 if exists_1(element_8):
#                     AirtestBase().click_5(element_8)
#                 elif exists_1(element_7):
#                     log.info('完成！')
#                     # break
#                 AirtestBase().up_or_down('up')
#             else:
#                 AirtestBase().click_5(element_1)
#                 AirtestBase().click_5(element_3)
#
#     except Exception as e:
#         log.error(f'悬浮球返回首页出现异常，为：{e}')
#         raise e


def exists_1(filename):
    """
    断言图片存在，主要用于if判断
    """
    threshold = read_ini()['airtest_parameter']['threshold']
    Settings.FIND_TIMEOUT_TMP = 1.5
    if exists(Template(filename, threshold=float(threshold))):
        return True
    else:
        return False


if __name__ == '__main__':
    AirtestBase().login_hw()
    # AirtestBase().click_5(r"D:\airtest_applets\element_picture\我的.png")
